package com.baizhi.controller;

import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import com.baizhi.util.ImageCodeUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

@CrossOrigin //处理跨域
@RestController
@RequestMapping("admin")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);
    @Resource
    AdminService adminService;

    @PostMapping("getImageCodes")
    public String getImageCodes(HttpServletRequest request){

        //获取验证码随机字符
        String code = ImageCodeUtil.getSecurityCode();
        log.info("验证码为:{}",code);
        //存储验证码随机字符
        request.getServletContext().setAttribute("code",code);
        //生产验证码图片将验证码图片转为Base64格式
        String imgBase64 =null;
        try {
            imgBase64 = ImageCodeUtil.careateImgBase64(code);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return imgBase64;
    }
    @RequestMapping("login")
    public HashMap<String, Object> login(@RequestBody Admin admin,String enCode ){
        log.info("admin:{}",admin);
        log.info("enCode:{}",enCode);
        HashMap<String, Object> map = adminService.login(admin, enCode);
        return map;
    }
    @PostMapping("logout")
    public void logout(HttpServletRequest request){
        log.info("退出登录");
        request.getServletContext().removeAttribute("admin");
    }
    @RequestMapping("queryAllPage")
    public HashMap<String,Object> queryAllPage(Integer page,Integer pageSize){
        HashMap<String, Object> map = adminService.queryAllPage(page, pageSize);
        return map;
    }
    @RequestMapping("delete")
    public HashMap<String,Object> delete(@RequestBody Admin admin){
        log.info("删除得id:{}",admin);
        HashMap<String, Object> map = adminService.delete(admin.getId());
        return map;
    }
    @RequestMapping("add")
    public HashMap<String,Object> add(@RequestBody Admin admin){
        log.info("添加的对象:{}",admin);
        HashMap<String, Object> map = adminService.add(admin);
            return map;
    }
    @RequestMapping("queryById")
    public Admin queryById(String id){

        return adminService.queryById(id);
    }
    @RequestMapping("update")
    public HashMap<String,Object>update(@RequestBody Admin admin){
       return adminService.update(admin);
    }
}
